import axios from 'axios';
import {Message} from 'element-ui';
import {localUitl} from "../utils/localUitl";
import {format} from "./format";


const service = axios.create({
  timeout: 0,
  withCredentials: false, // 是否允许带cookie这些
  headers: {
    "Content-Type": "application/json;charset=UTF-8"
  }
})

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    console.log("request", config);
    if (config.url.indexOf("pwdLogin") == -1 && config.url.indexOf("leftMenu") == -1 && config.headers.sendKey != "getUserN") {
      config.headers["access_token"] = localUitl.getToken();
    }

    return config;
  },
  error => {
    return Promise.reject(error.data.error.message);
  }
);

//返回状态判断(添加响应拦截器)
service.interceptors.response.use(
  res => {
    console.log("response", res);
    let sendKey = res.config.headers.sendKey;
    //TODO 看是否需要格式化逻辑处理
    if (format[sendKey]) {
      return format[sendKey](res);
    } else {
      return res;
    }
  },
  error => {
    let data = error.response.data.msg;
    Message({
      message: data || error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error);
  }
);

export default service;

